#include "EventLoopThreadPool.h"
#include "EventLoop.h"
#include "EventLoopThread.h"

std::map<std::thread::id, std::shared_ptr<std::mutex>> readLockMap_;

EventLoopThreadPool::EventLoopThreadPool(EventLoop* baseLoop)
    : baseLoop_(baseLoop),
    started_(false),
    numThreads_(0),
    next_(0)
{
}

EventLoopThreadPool::~EventLoopThreadPool()
{
  // LOG_TRACE << "~EventLoopThreadPool()";
}

// 创建EventLoop线程池
void EventLoopThreadPool::start()
{
    assert(!started_);
    baseLoop_->assertInLoopThread();

    started_ = true;

    for (int i = 0; i < numThreads_; ++i)
    {
        std::cout << "EventLoopThread num [" << i << "] was created" << endl;
        std::shared_ptr<EventLoopThread> t(new EventLoopThread());
        threads_.push_back(t);
        loops_.push_back(t->startLoop());
        readLockMap_[t->tid()] = make_shared<std::mutex>();
    }
}

// 返回EventLoop线程池中第next_个线程
EventLoop* EventLoopThreadPool::getNextLoop()
{
    baseLoop_->assertInLoopThread();
    EventLoop* loop = baseLoop_;

    if (!loops_.empty())
    {
        // round-robin
        loop = loops_[next_];
        ++next_;
        if (static_cast<size_t>(next_) >= loops_.size())
        {
            next_ = 0;
        }
    }
    return loop;
}

